<template>
	<view class="add-task-page" :style="{background: backgroundGradient}">
		<!-- 科技风格背景 -->
		<view class="tech-background">
			<view class="particles-container">
				<view v-for="i in 20" :key="i" class="particle" :style="getParticleStyle(i)"></view>
			</view>
			<view class="circuit-board">
				<view class="circuit-line horizontal line-1" :style="{background: circuitGradient}"></view>
				<view class="circuit-line horizontal line-2" :style="{background: circuitGradient}"></view>
				<view class="circuit-line vertical line-3" :style="{background: circuitGradient}"></view>
				<view class="circuit-line vertical line-4" :style="{background: circuitGradient}"></view>
			</view>
			<view class="glow-orb orb-1" :style="{background: orbGradient1}"></view>
			<view class="glow-orb orb-2" :style="{background: orbGradient2}"></view>
			<view class="glow-orb orb-3" :style="{background: orbGradient3}"></view>
			<view class="scan-line" :style="{background: scanGradient, boxShadow: scanShadow}"></view>
		</view>

		<!-- 状态栏占位 -->
		<view class="status-bar"></view>
	
		<!-- 主要内容区域 -->
		<view class="main-content">
			<view class="title-section">
				<view class="title-header">
					<view class="navbar-left" @click="handleCancel">
						<text class="back-icon">←</text>
					</view>
					<text class="main-title">✨ 创建新任务</text>
				</view>
				<text class="sub-title">填写任务信息，开始你的计划</text>
			</view>

			<!-- 表单卡片 -->
			<view class="form-container">
				<view class="form-card" :style="{borderColor: cardBorderColor}">
					<uni-forms :model="newTask" ref="taskRef" :rules="rules" class="task-form">
						<!-- 任务名称 -->
						<view class="form-section">
							<view class="form-row">
								<view class="form-label">
									<text class="section-icon">📝</text>
									<text class="section-title">任务名称</text>
									<text class="required-mark">*</text>
								</view>
								<view class="form-input">
									<uni-forms-item name="taskName" class="form-item-custom">
										<uni-easyinput 
											v-model="newTask.taskName" 
											placeholder="请输入任务名称" 
											clearable 
											maxlength="15" 
											class="custom-input" 
										/>
									</uni-forms-item>
								</view>
							</view>
						</view>

						<!-- 任务图标 -->
						<view class="form-section">
							<view class="form-row">
								<view class="form-label">
									<text class="section-icon">🎨</text>
									<text class="section-title">任务图标</text>
									<text class="required-mark">*</text>
								</view>
								<view class="form-input">
									<uni-forms-item name="icon" class="form-item-custom">
										<view class="icon-upload-area">
											<uni-file-picker 
												limit="1" 
												:del-icon="false" 
												:disable-preview="true" 
												:imageStyles="imageStyles"
												:auto-upload="false" 
												file-extname="png,jpg" 
												v-model="taskIcon" 
												file-mediatype="image"
												@select="handleIconSelect" 
											/>
											<text class="upload-tip">点击上传任务图标</text>
										</view>
									</uni-forms-item>
								</view>
							</view>
						</view>

						<!-- 任务标签 -->
						<view class="form-section">
							<view class="form-row">
								<view class="form-label">
									<text class="section-icon">🏷️</text>
									<text class="section-title">任务标签</text>
									<text class="required-mark">*</text>
								</view>
								<view class="form-input">
									<uni-forms-item name="tags" class="form-item-custom">
										<uni-data-checkbox 
											v-model="newTask.tags" 
											:localdata="tagOptions" 
											:multiple="false" 
											check-strictly 
											class="custom-checkbox" 
										/>
									</uni-forms-item>
								</view>
							</view>
						</view>

						<!-- 任务分数 -->
						<view class="form-section">
							<view class="form-row">
								<view class="form-label">
									<text class="section-icon">⭐</text>
									<text class="section-title">任务分数</text>
									<text class="required-mark">*</text>
								</view>
								<view class="form-input">
									<uni-forms-item name="score" class="form-item-custom">
										<view class="score-input-wrapper">
											<uni-number-box 
												v-model="newTask.score" 
												placeholder="请输入任务分数" 
												:min="1" 
												:max="100" 
												class="custom-number-box" 
											/>
											<text class="score-unit">分</text>
										</view>
									</uni-forms-item>
								</view>
							</view>
						</view>
					</uni-forms>
				</view>
			</view>

			<!-- 底部操作按钮 -->
			<view class="bottom-actions">
				<button class="action-btn cancel-btn" @click="handleCancel">
					<text class="btn-text">取消</text>
				</button>
				<button 
					class="action-btn confirm-btn" 
					:style="{background: buttonGradient, boxShadow: buttonShadow}" 
					@click="handleSubmitNewTask" 
					:loading="loading"
				>
					<text class="btn-text">创建任务</text>
				</button>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { addTaskAPI } from '@/services/task'
import { uploadAvatarAPI } from '@/services/user'
import { TaskItem, AvatarUploadResult } from '@/types'
import { baseURL } from '@/utils/config'
import { FileType } from '@/types'
import { getThemeStyles } from '@/stores/theme'

const taskRef = ref(null)
const loading = ref(false)
const themeColors = ref<any>({})

onMounted(() => {
	themeColors.value = getThemeStyles()
})

const newTask = ref<TaskItem>({
	taskName: '',
	icon: '',
	score: 1,
	tags: '学习',
	status: 0
})

const taskIcon = ref<FileType[]>([])

const imageStyles = ref({
	width: '90rpx',
	height: '90rpx',
	border: {
		color: '#eee',
		width: '1px',
		style: 'solid',
		radius: '50%'
	}
})

const tagOptions = ref([
	{ value: '学习', text: '学习' },
	{ value: '家务', text: '家务' }
])

const rules = ref({
	taskName: {
		rules: [{ required: true, message: '请输入任务名称' }]
	},
	icon: {
		rules: [{ required: true, message: '请选择任务图标' }]
	},
	tags: {
		rules: [{ required: true, message: '请选择任务标签' }]
	},
	score: {
		rules: [{ required: true, message: '请输入任务分数' }]
	}
})

const handleIconSelect = (file: any) => {
	console.log('选择的图标文件:', file);
	if (file && file.tempFiles && file.tempFiles.length > 0) {
		const tempFile = file.tempFiles[0];
		console.log('临时文件对象:', tempFile);
		
		// uni-file-picker组件返回的文件对象通常包含path属性
		const filePath = tempFile.path || tempFile.url || tempFile.tempFilePath;
		
		if (!filePath) {
			console.error('无法获取文件路径，文件对象:', tempFile);
			uni.showToast({
				title: '文件路径获取失败',
				icon: 'none'
			});
			return;
		}
		
		console.log('提取的文件路径:', filePath);
		uploadAvatarAPI(filePath).then(response => {
			handleIconUploadSuccess(response as AvatarUploadResult)
		}).catch(handleIconUploadFail)
	}
}

const handleIconUploadSuccess = (response: AvatarUploadResult) => {
	if (response && response.url) {
		newTask.value.icon = response.url
		taskIcon.value = [{
			url: baseURL + response.url,
			extname: response.url.split('.').pop() || '',
			name: response.url.split('/').pop() || 'task_icon'
		}]
		
		// 清除icon字段的验证错误
		if (taskRef.value) {
			taskRef.value.clearValidate('icon');
		}
		
		uni.showToast({ title: '图标上传成功', icon: 'success' })
	} else {
		handleIconUploadFail(new Error('响应数据格式不正确'))
	}
}

const handleIconUploadFail = (error: any) => {
	console.error('图标上传失败:', error)
	uni.showToast({ title: '图标上传失败，请重试', icon: 'none' })
	taskIcon.value = []
}

const handleSubmitNewTask = async () => {
	if (loading.value) return
	try {
		loading.value = true
		await taskRef.value.validate()
		if (!newTask.value.icon) {
			uni.showToast({ title: '请先上传任务图标', icon: 'none' })
			return
		}
		await addTaskAPI(newTask.value)
		uni.showToast({ title: '任务添加成功', icon: 'success' })
		setTimeout(() => {
			uni.navigateBack()
		}, 500)
	} finally {
		loading.value = false
	}
}

const handleCancel = () => {
	uni.navigateBack()
}

// 十六进制颜色转RGB
const hexToRgb = (hex: string) => {
	const color = hex.replace('#', '')
	const r = parseInt(color.substring(0, 2), 16)
	const g = parseInt(color.substring(2, 4), 16)
	const b = parseInt(color.substring(4, 6), 16)
	return `${r}, ${g}, ${b}`
}

// 计算属性
const backgroundGradient = computed(() => 
	themeColors.value.primaryGradient || 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
)

const accentColor = computed(() => themeColors.value.accentColor || '#667eea')

const accentColorRgb = computed(() => hexToRgb(accentColor.value))

const cardBorderColor = computed(() => 
	`rgba(${accentColorRgb.value}, 0.3)`
)

const buttonGradient = computed(() => 
	themeColors.value.primaryGradient || 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
)

const buttonShadow = computed(() => 
	`0 8rpx 24rpx rgba(${accentColorRgb.value}, 0.4)`
)

// 生成粒子样式
const getParticleStyle = (index: number) => {
	const size = Math.random() * 4 + 2;
	const duration = Math.random() * 10 + 10;
	const delay = Math.random() * 5;
	const startX = Math.random() * 100;
	const startY = Math.random() * 100;
	
	return {
		width: `${size}rpx`,
		height: `${size}rpx`,
		left: `${startX}%`,
		top: `${startY}%`,
		animationDuration: `${duration}s`,
		animationDelay: `${delay}s`,
		background: `rgba(${accentColorRgb.value}, 0.6)`,
		boxShadow: `0 0 10rpx rgba(${accentColorRgb.value}, 0.8)`
	};
}

// 加深颜色
const darkenColor = (hex: string, factor: number) => {
	const color = hex.replace('#', '')
	const r = Math.floor(parseInt(color.substring(0, 2), 16) * factor)
	const g = Math.floor(parseInt(color.substring(2, 4), 16) * factor)
	const b = Math.floor(parseInt(color.substring(4, 6), 16) * factor)
	return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`
}

// 科技背景相关计算属性
const circuitGradient = computed(() => 
	`linear-gradient(90deg, transparent 0%, rgba(${accentColorRgb.value}, 0.4) 50%, transparent 100%)`
)

const orbGradient1 = computed(() => 
	`radial-gradient(circle, rgba(${accentColorRgb.value}, 0.3) 0%, transparent 70%)`
)

const orbGradient2 = computed(() => {
	const secondary = themeColors.value.secondaryColor || '#764ba2'
	const rgb = hexToRgb(secondary)
	return `radial-gradient(circle, rgba(${rgb}, 0.25) 0%, transparent 70%)`
})

const orbGradient3 = computed(() => {
	const info = themeColors.value.infoColor || '#00bfff'
	const rgb = hexToRgb(info)
	return `radial-gradient(circle, rgba(${rgb}, 0.2) 0%, transparent 70%)`
})

const scanGradient = computed(() => 
	`linear-gradient(90deg, transparent 0%, rgba(${accentColorRgb.value}, 0.8) 50%, transparent 100%)`
)

const scanShadow = computed(() => 
	`0 0 20rpx rgba(${accentColorRgb.value}, 0.8)`
)
</script>

<style lang="scss" scoped>
.add-task-page {
	position: relative;
	min-height: 100vh;
	padding: 0;
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
}

/* 状态栏占位 */
.status-bar {
	height: var(--status-bar-height);
	background: transparent;
}

/* 自定义导航栏 */
.custom-navbar {
	position: relative;
	display: flex;
	align-items: center;
	height: 88rpx;
	padding: 0 32rpx;
	z-index: 10;
	backdrop-filter: blur(20rpx);
	background: rgba(0, 0, 0, 0.1);
}

.navbar-left {
	width: 80rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 12rpx;
	background: rgba(255, 255, 255, 0.1);
	backdrop-filter: blur(10rpx);
	transition: all 0.3s ease;
	margin-right: 24rpx;
	flex-shrink: 0;
	
	&:active {
		background: rgba(255, 255, 255, 0.2);
		transform: scale(0.95);
	}
}

.back-icon {
	font-size: 36rpx;
	color: rgba(255, 255, 255, 0.9);
	font-weight: bold;
}

.navbar-center {
	flex: 1;
	display: flex;
	justify-content: center;
	align-items: center;
}

.navbar-title {
	font-size: 36rpx;
	font-weight: 600;
	color: rgba(255, 255, 255, 0.9);
	text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
}

.navbar-right {
	width: 80rpx;
}

/* 主要内容区域 */
.main-content {
	flex: 1;
	padding: 0 32rpx 32rpx;
	z-index: 1;
}

/* 页面标题区域 */
.title-section {
	padding: 40rpx 0 32rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.title-header {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	width: 100%;
	margin-bottom: 16rpx;
}

.main-title {
	font-size: 48rpx;
	font-weight: 700;
	color: rgba(255, 255, 255, 0.95);
	letter-spacing: 2rpx;
	text-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.3);
	flex: 1;
}

.sub-title {
	font-size: 28rpx;
	color: rgba(255, 255, 255, 0.7);
	text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
}

/* 表单容器 */
.form-container {
	margin-bottom: 120rpx;
}

.form-card {
	background: rgba(0, 0, 0, 0.25);
	backdrop-filter: blur(20rpx);
	border-radius: 24rpx;
	border: 1rpx solid;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.4);
	overflow: hidden;
}

/* 表单分组 */
.form-section {
	padding: 32rpx;
	border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
	
	&:last-child {
		border-bottom: none;
	}
}

.form-row {
	display: flex;
	align-items: flex-start;
	gap: 24rpx;
	padding: 16rpx 0;
}

.form-label {
	display: flex;
	align-items: center;
	min-width: 200rpx;
	flex-shrink: 0;
	padding-top: 20rpx;
}

.form-input {
	flex: 1;
	min-width: 0;
}

.section-icon {
	font-size: 32rpx;
	margin-right: 12rpx;
}

.section-title {
	font-size: 28rpx;
	font-weight: 600;
	color: rgba(255, 255, 255, 0.9);
	margin-right: 8rpx;
}

.required-mark {
	color: #ff6b6b;
	font-size: 28rpx;
	font-weight: bold;
}

/* 表单项样式 */
.form-item-custom {
	margin: 0;
}

/* 图标上传区域 */
.icon-upload-area {
	display: flex;
	flex-direction: column;
	gap: 12rpx;
	width: 100%;
}

.upload-tip {
	font-size: 22rpx;
	color: rgba(255, 255, 255, 0.6);
	margin-left: 8rpx;
}

/* 分数输入包装器 */
.score-input-wrapper {
	display: flex;
	align-items: center;
	gap: 16rpx;
}

.score-unit {
	font-size: 28rpx;
	color: rgba(255, 255, 255, 0.8);
	font-weight: 500;
}

/* 底部操作按钮 */
.bottom-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 24rpx 32rpx;
	padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
	background: rgba(0, 0, 0, 0.3);
	backdrop-filter: blur(20rpx);
	border-top: 1rpx solid rgba(255, 255, 255, 0.1);
	display: flex;
	gap: 24rpx;
	z-index: 10;
}

.action-btn {
	flex: 1;
	height: 96rpx;
	border-radius: 24rpx;
	border: none;
	font-size: 32rpx;
	font-weight: 600;
	transition: all 0.3s ease;
	position: relative;
	overflow: hidden;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0;
	
	&:active {
		transform: scale(0.98);
	}
}

.cancel-btn {
	background: rgba(255, 255, 255, 0.1);
	border: 2rpx solid rgba(255, 255, 255, 0.3);
	
	.btn-text {
		color: rgba(255, 255, 255, 0.9);
		line-height: 1;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	&:active {
		background: rgba(255, 255, 255, 0.2);
	}
}

.confirm-btn {
	.btn-text {
		color: #fff;
		line-height: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		z-index: 2;
	}
	
	&:before {
		content: '';
		position: absolute;
		top: 50%;
		left: 50%;
		width: 0;
		height: 0;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.3);
		transform: translate(-50%, -50%);
		transition: width 0.6s, height 0.6s;
		z-index: 1;
	}
	
	&:active:before {
		width: 300rpx;
		height: 300rpx;
	}
}

/* 表单组件样式优化 */
.form-card :deep(.uni-easyinput) {
	background: rgba(255, 255, 255, 0.08) !important;
	border: 1rpx solid rgba(255, 255, 255, 0.2) !important;
	border-radius: 16rpx !important;
	overflow: hidden;
}

.form-card :deep(.uni-easyinput__content) {
	background: transparent !important;
	border: none !important;
	padding: 0 !important;
}

.form-card :deep(.uni-easyinput__content-input) {
	color: rgba(255, 255, 255, 0.9) !important;
	background: transparent !important;
	border: none !important;
	padding: 20rpx 24rpx !important;
	font-size: 28rpx !important;
	line-height: 1.4 !important;
	height: 80rpx !important;
	box-sizing: border-box !important;
}

.form-card :deep(.uni-easyinput__placeholder-class) {
	color: rgba(255, 255, 255, 0.5) !important;
	font-size: 28rpx !important;
}

.form-card :deep(.uni-data-checklist .checklist-group .checklist-box) {
	background: rgba(255, 255, 255, 0.08) !important;
	border: 1rpx solid rgba(255, 255, 255, 0.2) !important;
	border-radius: 16rpx !important;
	margin: 8rpx !important;
	padding: 16rpx 20rpx !important;
	height: 60rpx !important;
	box-sizing: border-box !important;
	display: flex !important;
	align-items: center !important;
	justify-content: center !important;
}

.form-card :deep(.uni-data-checklist .checklist-group .checklist-box .checklist-text) {
	color: rgba(255, 255, 255, 0.9) !important;
	font-size: 28rpx !important;
}

.form-card :deep(.uni-numbox) {
	background: rgba(255, 255, 255, 0.08) !important;
	border: 1rpx solid rgba(255, 255, 255, 0.2) !important;
	border-radius: 16rpx !important;
	overflow: hidden;
}

.form-card :deep(.uni-numbox__value) {
	color: rgba(255, 255, 255, 0.9) !important;
	background: transparent !important;
	border: none !important;
	font-size: 28rpx !important;
	text-align: center !important;
	padding: 0 16rpx !important;
	height: 60rpx !important;
	box-sizing: border-box !important;
	display: flex !important;
	align-items: center !important;
	justify-content: center !important;
	line-height: 1 !important;
}

.form-card :deep(.uni-numbox__minus),
.form-card :deep(.uni-numbox__plus) {
	background: rgba(255, 255, 255, 0.1) !important;
	color: rgba(255, 255, 255, 0.8) !important;
	border: none !important;
	width: 60rpx !important;
	height: 60rpx !important;
	display: flex !important;
	align-items: center !important;
	justify-content: center !important;
}

.form-card :deep(.uni-file-picker__container) {
	background: rgba(255, 255, 255, 0.08) !important;
	border: 1rpx solid rgba(255, 255, 255, 0.2) !important;
	border-radius: 16rpx !important;
	padding: 15rpx !important;
	height: 120rpx !important;
	box-sizing: border-box !important;
	display: flex !important;
	align-items: center !important;
	justify-content: center !important;
}

.form-card :deep(.uni-file-picker__files) {
	display: flex !important;
	align-items: center !important;
	justify-content: center !important;
}

.form-card :deep(.uni-file-picker__files-item) {
	margin: 0 !important;
}

/* 科技风格背景 */
.tech-background {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	overflow: hidden;
	z-index: 0;
}

/* 粒子容器 */
.particles-container {
	position: absolute;
	width: 100%;
	height: 100%;
	overflow: hidden;
}

.particle {
	position: absolute;
	border-radius: 50%;
	animation: particleFloat 15s linear infinite;
}

@keyframes particleFloat {
	0% {
		transform: translateY(0) translateX(0);
		opacity: 0;
	}
	10% {
		opacity: 1;
	}
	90% {
		opacity: 1;
	}
	100% {
		transform: translateY(-100vh) translateX(50rpx);
		opacity: 0;
	}
}

/* 电路板线条 */
.circuit-board {
	position: absolute;
	width: 100%;
	height: 100%;
}

.circuit-line {
	position: absolute;
}

.circuit-line.horizontal {
	width: 100%;
	height: 2rpx;
	animation: circuitPulse 3s ease-in-out infinite;
}

.circuit-line.vertical {
	width: 2rpx;
	height: 100%;
	animation: circuitPulse 3s ease-in-out infinite;
}

.line-1 {
	top: 20%;
	animation-delay: 0s;
}

.line-2 {
	top: 60%;
	animation-delay: 1.5s;
}

.line-3 {
	left: 25%;
	animation-delay: 0.75s;
}

.line-4 {
	left: 75%;
	animation-delay: 2.25s;
}

@keyframes circuitPulse {
	0%, 100% {
		opacity: 0.2;
	}
	50% {
		opacity: 1;
	}
}

/* 发光球体 */
.glow-orb {
	position: absolute;
	border-radius: 50%;
	filter: blur(60rpx);
	animation: orbFloat 8s ease-in-out infinite;
}

.orb-1 {
	top: 10%;
	left: 10%;
	width: 300rpx;
	height: 300rpx;
	animation-delay: 0s;
}

.orb-2 {
	top: 50%;
	right: 10%;
	width: 250rpx;
	height: 250rpx;
	animation-delay: 2.5s;
}

.orb-3 {
	bottom: 15%;
	left: 50%;
	width: 280rpx;
	height: 280rpx;
	animation-delay: 5s;
}

@keyframes orbFloat {
	0%, 100% {
		transform: translate(0, 0) scale(1);
	}
	33% {
		transform: translate(50rpx, -50rpx) scale(1.2);
	}
	66% {
		transform: translate(-30rpx, 30rpx) scale(0.9);
	}
}

/* 扫描线 */
.scan-line {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 4rpx;
	animation: scanMove 4s linear infinite;
}

@keyframes scanMove {
	0% {
		transform: translateY(0);
		opacity: 0;
	}
	10% {
		opacity: 1;
	}
	90% {
		opacity: 1;
	}
	100% {
		transform: translateY(100vh);
		opacity: 0;
	}
}
</style>
